const { getCurrentConfig } = require('../config.js')

// 用于管理loading状态的计数器
let loadingCount = 0;

function showLoading() {
  loadingCount++;
  if (loadingCount === 1) {
    wx.showLoading({ title: '加载中...', mask: true });
  }
}

function hideLoading() {
  loadingCount--;
  if (loadingCount <= 0) {
    loadingCount = 0;
    wx.hideLoading();
  }
}

function request({ url, method = 'GET', data = {}, header = {
    "Content-Type":"application/json;charset=UTF-8"
  }, shouldShowLoading = true }) {
  // 获取当前环境的API基础地址
  const config = getCurrentConfig();
  const baseUrl = config.apiBaseUrl;
  
  console.log('当前环境:', config.envName, '正在发起网络请求地址：'+ (baseUrl + url))
  // 自动携带 token
  const token = wx.getStorageSync('token')
  if (token) {
    header['Authorization'] = 'Bearer ' + token
  }

  if (shouldShowLoading) showLoading();
  return new Promise((resolve, reject) => {
    wx.request({
      url: baseUrl + url,
      method,
      data,
      header,
      success: res => {
        if (shouldShowLoading) hideLoading();
        if (res.data && res.data.code === 401) {
          wx.removeStorageSync('token')
          const app = (typeof getApp === 'function') ? getApp() : null
          if (app && typeof app.silentLogin === 'function') {
            app.silentLogin()
          }
          const prevCount = wx.getStorageSync('auth401Count') || 0
          const newCount = prevCount + 1
          wx.setStorageSync('auth401Count', newCount)
          if (newCount > 10) {
            wx.showToast({ title: '请重新登录', icon: 'none' })
            setTimeout(() => {
              wx.redirectTo({ url: '/pages/login/login' })
            }, 400)
          } else {
            let errorMsg = res.data.msg || '登录失效'
            // wx.showToast({ title: `${errorMsg}，自动重试(${newCount}/10)`, icon: 'none' })
          }
          reject(res)
        } else if (res.data.code === 200 ) {
          wx.setStorageSync('auth401Count', 0)
          if (res.data.data || res.data.data === 0) {
            resolve(res.data.data)
          } else {
            // 有些情况是没有对象返回，直接返回字符串（因为后端AjaxResult构造的问题，如果是字符串就不会返回data，而是msg）
            resolve(res.data.msg)
          }
        } else {
          wx.showToast({ title: res.data && res.data.msg ? res.data.msg : '请求失败', icon: 'none' })
          reject(res)
        }
      },
      fail: err => {
        if (shouldShowLoading) hideLoading();
        const errorInfo = `网络异常: ${baseUrl}/${url}\n方式:${method}\n状态: ${err.errMsg || '未知错误'}`;
        wx.showToast({ title: errorInfo, icon: 'none', duration: 5000 })
        reject(err)
      }
    })
  })
}

module.exports = {
  get(url, data = {}, header = {}, shouldShowLoading = true) {
    return request({ url, method: 'GET', data, header, shouldShowLoading })
  },
  post(url, data = {}, header = {}, shouldShowLoading = true) {
    return request({ url, method: 'POST', data, header, shouldShowLoading })
  },
  put(url, data = {}, header = {}, shouldShowLoading = true) {
    return request({ url, method: 'PUT', data, header, shouldShowLoading })
  },
  delete(url, data = {}, header = {}, shouldShowLoading = true) {
    return request({ url, method: 'DELETE', data, header, shouldShowLoading })
  }
} 